import { Form as AntdForm, Col, DatePicker, FormInstance, Input, Row } from "antd";
import React, { forwardRef, ForwardRefRenderFunction, useImperativeHandle, useMemo, useState } from "react";
import { CommonComponentProps } from "@/pages/lowCodeEditorPlus/interface";
import dayjs from "dayjs";

export interface FormRef {
  submit: () => void;
  selfDataProperties:{
    form: Record<string, any>
  }
}

const Form: ForwardRefRenderFunction<FormRef, Omit<CommonComponentProps, "ref">> = (
  { children, onFinish, layout, gutter },
  ref
) => {
  const [form] = AntdForm.useForm();
  useImperativeHandle(
    ref,
    () => {
      return {
        submit: () => {
          form.submit();
        },
        selfDataProperties:{
          form: form.getFieldsValue
        }
      };
    },
    [form.getFieldsValue()]
  );

  const formItems = useMemo(() => {
    return React.Children.map(children, (item: any) => {
      return {
        label: item.props?.label,
        name: item.props?.name,
        type: item.props?.type,
        id: item.props?.id,
        rules: item.props?.rules,
        span: item.props?.span,
      };
    });
  }, [children]);

  async function save(values: any) {
    Object.keys(values).forEach(key => {
      if (dayjs.isDayjs(values[key])) {
        values[key] = values[key].format("YYYY-MM-DD");
      }
    });
    onFinish(values);
  }
  return (
    <AntdForm
      layout={layout}
      // labelCol={{ span: 5 }}
      // wrapperCol={{ span: 18 }}
      form={form}
      onFinish={save}
    >
      <Row gutter={gutter}>
        {formItems.map((item: any) => {
          return (
            <Col span={item.span} key={item.name}>
              <AntdForm.Item
                name={item.name}
                label={item.label}
                rules={
                  item.rules === "required"
                    ? [
                        {
                          required: true,
                          message: "不能为空",
                        },
                      ]
                    : []
                }
              >
                {item.type === "input" && <Input />}
                {item.type === "date" && <DatePicker />}
              </AntdForm.Item>
            </Col>
          );
        })}
      </Row>
    </AntdForm>
  );
};

export default forwardRef(Form);
